package com.print.androidprintproject.page;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.print.androidprintproject.R;
import com.print.androidprintproject.print.PrintJobService;
import com.print.printlib.utils.PrintUtils;
import org.vudroid.pdfdroid.codec.PdfContext;
import org.vudroid.pdfdroid.codec.PdfDocument;
import org.vudroid.pdfdroid.codec.PdfPage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class PdfPrintActivity extends BaseActivity implements OnClickListener {
//	private Button btnPrintPdf;
	private Button btnPrintthis;
	private Button btnPrevious;
	private Button btnNext;
	private Button btnChosePdf;
	private ImageView ivShowPdf;
	private TextView tvShowPage;
	private LinearLayout header;
	private int currentCount = -1;
	private int pageCount = -1;
	private ArrayList<Bitmap> bitmaps;
	private String path = null;
	private String TAG = "com.printer.demo.ui";
	private PrintJobService printJobService;

	public static int screenWidth, screenHeight;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_print_pdf);
//		btnPrintPdf = findViewById(R.id.btn_printpdf);
		btnPrevious = findViewById(R.id.btn_pre);
		btnNext = findViewById(R.id.btn_next);
		btnPrintthis = findViewById(R.id.btn_printthis);
		btnChosePdf = findViewById(R.id.btn_choose_pdf_file);
		btnChosePdf.setOnClickListener(this);
//		btnPrintPdf.setOnClickListener(this);
		btnPrevious.setOnClickListener(this);
		btnNext.setOnClickListener(this);
		btnPrintthis.setOnClickListener(this);
		ivShowPdf = findViewById(R.id.iv_showpdf);
		tvShowPage = findViewById(R.id.tv_showpage);
		header = findViewById(R.id.ll_headerview_Pdf_Printactivity);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		initHeader();

		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		screenWidth = outMetrics.widthPixels;
		screenHeight = outMetrics.heightPixels;

		bitmaps = new ArrayList<>();
		printJobService = PrintJobService.getObject(this, null);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	/**
	 * 初始化标题上的信息
	 */
	private void initHeader() {
		setHeaderLeftText(header, getString(R.string.back), new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		setHeaderLeftImage(header, new OnClickListener() {// 初始化了
			// headerConnecedState
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		headerConnecedState.setText(getTitleState());
		setHeaderCenterText(header, getString(R.string.headview_PdfPrint));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_printthis:
			if(bitmaps.size()>0) {
				printJobService.printPicture(bitmaps.get(currentCount-1), 0);
			}
			break;
		case R.id.btn_pre:
			if(bitmaps.size()>0 && currentCount>1) {
				currentCount--;
				showPdfPage(currentCount);
			}
			break;
		case R.id.btn_next:
			if(bitmaps.size()>0 && currentCount<pageCount) {
				currentCount++;
				showPdfPage(currentCount);
			}
			break;
		case R.id.btn_choose_pdf_file:
			InputStream input = null;
			input = this.getClass().getResourceAsStream("/assets/print_file.pdf");
			try {
				int readNum = input.available();
				int packSize, readSize = 0;
				byte []btRead = new byte[readNum];
				while (readNum>0) {
					packSize = input.read(btRead, readSize, readNum);
					readSize += packSize;
					readNum -= packSize;
				}
				PrintUtils.saveHexFile(btRead, "print_file.pdf");
			} catch (IOException e) {
				e.printStackTrace();
			}
			this.path = Environment.getExternalStorageDirectory() + "/print/" + "print_file.pdf";
			new InnerAsyncTask().execute();
			break;
		}

	}

	private class InnerAsyncTask extends AsyncTask<Void, Void, ArrayList<Bitmap>> {

		@Override
		protected ArrayList<Bitmap> doInBackground(Void... params) {
			String path = Environment.getExternalStorageDirectory() + "/print/";
			PdfContext codecContext = new PdfContext();
			PdfDocument pdfDocument = (PdfDocument) codecContext.openDocument(path + "print_file.pdf");
			int pageCount = pdfDocument.getPageCount();
			for(int i=1; i<=pageCount; ++i) {
				PdfPage pdfPage = (PdfPage) pdfDocument.getPage(1);
				RectF rectF = new RectF(0.0f, 0.0f, 1.0f, 1.0f);
				Bitmap bitmap = pdfPage.renderBitmap(384, pdfPage.getHeight()*384/pdfPage.getWidth(), rectF);
				bitmaps.add(bitmap);
			}
			return bitmaps;
		}

		protected void onPostExecute(ArrayList<Bitmap> result) {
			pageCount = result.size();
			currentCount = 1;
			showPdfPage(currentCount);
		}
	}

	private void showPdfPage(int curpage) {
		tvShowPage.setText(curpage + "/" + pageCount);
		Matrix matrix = new Matrix();
		float fx;
		if(screenWidth > bitmaps.get(curpage-1).getWidth())
			fx = 0.5f;
		else
			fx = (float)screenWidth / (float)bitmaps.get(curpage-1).getWidth();
		matrix.setScale(fx, fx);
		ivShowPdf.setScaleType(ImageView.ScaleType.MATRIX);
		ivShowPdf.setImageMatrix(matrix);
		ivShowPdf.setImageBitmap(bitmaps.get(curpage-1));
	}
}
